# State Code:
def GetOldStates():
    import sys

    try: states = sys.oldStates
    except AttributeError:
        states = sys.oldStates = []

    return states

def RegisterOldState(**kwd):
    states = GetOldStates()
    states.insert(0, kwd)

def PopOldState():
    states = GetOldStates()
    del states[0]

def GetLastState():
    return GetOldStates()[0]

def DoInLastState(function, *args, **kwd):
    state = GetLastState()

    import sys
    thisStdin = sys.stdin
    thisStdout = sys.stdout

    sys.stdin = state['stdin']
    sys.stdout = state['stdout']

    try: return function(*args, **kwd)
    finally:
        sys.stdin = thisStdin
        sys.stdout = thisStdout

# ExecuteCGI Patch:
##  RegisterOldState(sys_modules = old_module_dict,
##                   builtins = old_builtin,
##                   argv = old_argv,
##                   stdin = old_stdin,
##                   stdout = old_stdout,
##                   environ = old_env,
##                   cwd = old_cwd,
##                   file_type = old_file_type)
# 
##    PopOldState()

# And site usage:
try: from google.appengine.tools.dev_appserver import DoInLastState
except ImportError:
    info('DevAppserver debugging not available!')
    unavailable = True
else:
    unavailable = not isDevelopmentServer()

if unavailable:
    def DoInLastState(function, *args, **kwd):
        return function(*args, **kwd)
    def PDebug(function, *args, **kwd):
        return function(*args, **kwd)
    def PTrace(function):
        return function
else:
    from pdb import runcall, set_trace
    def PDebug(function, *args, **kwd):
        return DoInLastState(runcall, function, *args, **kwd)

    def PTrace(function):
        def tracedFunction(*args, **kwd):
            set_trace()
            return function(*args, **kwd)

        def statefulFunction(*args, **kwd):
            return DoInLastState(tracedFunction, *args, **kwd)

        statefulFunction.__name__ = function.__name__
        statefulFunction.__doc__ = function.__doc__
        return statefulFunction
